package kyssion.leetcode.num51_100;

import kyssion.leetcode.util.ListNode;

public class code83_删除列表中的重复元素1 {

    public static void main(String[] args) {
        ListNode node = ListNode.createListNode(new int[]{
                1,2,3,3,4,4,5});
        ListNode.showListNode(new code83_删除列表中的重复元素1().deleteDuplicates(node));
    }

    /**
     * 实现通用方法,可以删除任意数量的数据
     * @param head
     * @return
     */
    public ListNode deleteDuplicates(ListNode head) {
        return deleteSameItem(head, 2);
    }

    public ListNode deleteSameItem(ListNode head, int same) {
        if (same == 0) {
            return new ListNode(-1);
        }
        ListNode start = new ListNode(-1);
        start.next = head;
        ListNode itemBefore = start;
        ListNode item = start.next;
        int num = 1;
        while (item != null) {
            if (itemBefore !=start && itemBefore.val == item.val) {
                num++;
                if (num > same) {
                    item = item.next;
                } else {
                    itemBefore = itemBefore.next;
                    item = item.next;
                }
            } else {
                if (num > same) {
                    itemBefore.next = item;
                    itemBefore = item;
                    item = item.next;
                } else {
                    itemBefore = itemBefore.next;
                    item = item.next;
                }
                num = 1;
            }
        }
        if (num > same) {
            itemBefore.next = item;
        }
        return start.next;
    }
}
